package io.serializable;

import framework.AbstractTest;
import utils.Log;

import java.io.*;

/**
 * Created by shane on 2018/5/28.
 */
public class Blip3 extends AbstractTest implements Externalizable {

    private static final long serialVersionUID = -3614426234246004189L;
    private static final String TAG = "Blip3";

    private int i;
    private String s; // No initialzation

    public Blip3() {

        Log.vn("Blip3 constructor");
        // s, i not initialized
    }

    public Blip3(String x, int a) {

        Log.vn("Blip3(String x, int a)");
        s = x;
        i = a;
        // s & i initialized only in non-default constructor
    }


    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        Log.vn("Blip3 writeExternal");
        // You must do this
        out.writeObject(s);
        out.writeInt(i);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        Log.vn("Blip3 readExternal");
        s = (String)in.readObject();
        i = in.readInt();
    }

    @Override
    public String toString() {
        return s + i;
    }


    @Override
    public void test(String[] args) {
        super.test(args);
        String outPath = getDefTempFile(args);

        try {
            Log.vn("constructing objects");
            Blip3 blip3 = new Blip3("A String ", 47);
            Log.vn(blip3.toString());

            ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(outPath));
            Log.vn("saving objects:");
            o.writeObject(blip3);
            o.close();

            ObjectInputStream in = new ObjectInputStream(new FileInputStream(outPath));
            Log.vn("recovering objects:");
            blip3 = (Blip3) in.readObject();
            Log.vn(blip3.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected String getTag() {
        return TAG;
    }
}
